/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package transactions;

import item.Item;
import item.ItemInfo;
import java.sql.Date;
import java.util.Calendar;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import myJPA.Model;
import user.Customer;
import user.Employee;

/**
 *
 * @author ZIZI
 */
public class RentalList {
    
    
        public static boolean addRental(Customer c, Item item, Employee employee)
    {
        java.sql.Date today = new Date(java.util.Calendar.getInstance().getTimeInMillis());
        EntityManager manager = Model.getEntityManager();
        
        Item it= manager.find(Item.class, item.getId());
        if(it.getAvailableCopies() > 0)
        {
            Calendar c1 = Calendar.getInstance();
            Query q = manager.createNamedQuery("findCharge");
            q.setParameter("type", item.getType());
            ItemInfo info = (ItemInfo) q.getSingleResult();
            c1.setTime(today);
            c1.add(Calendar.DATE, info.getRentalPeriod());        
            java.sql.Date dateReturn = new java.sql.Date(c1.getTimeInMillis());
            Rental rental = new Rental(today, dateReturn ,c, item, employee, false);
            rental.save();
            it.setAvailableCopies(it.getAvailableCopies() - 1);
            it.save();

            return true;
        }
        else
            return false;
    }    
    
    public static boolean RecordReturn(Customer c, Item item, Employee employee)
    {
        java.sql.Date today = new Date(java.util.Calendar.getInstance().getTimeInMillis());
        EntityManager manager = Model.getEntityManager();
        Query q = manager.createNamedQuery("findRental1");
        q.setParameter("cus", c);
        q.setParameter("item", item);
       
        Rental rental = null;
        try 
        {
            rental = (Rental) q.getResultList().get(0);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        if(rental != null)
        {
            rental.setReturned(true);
            rental.update();
            ReservationMgt.placeItemOnHold(item);
            return true;
        }
        return false;
        
        
    }
        
        
        
}
